package com.yu.task.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.task.globalResult.R;
import com.yu.task.mapper.BlogMapper;
import com.yu.task.mapper.BlogTagMapper;
import com.yu.task.mapper.UserBlogMapper;
import com.yu.task.pojo.*;
import com.yu.task.service.BlogService;
import com.yu.task.service.BlogTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private UserBlogMapper userBlogMapper;

    @Autowired
    private BlogTagService blogTagService;

//    @Override
//    public List<Blog> getBlogTags() {
//        List<Blog> list = blogMapper.getBlogTags();
//        return list;
//
//    }

    @Override
    public Page<BlogTagVo> getBlogTagVo(int page, int size) {

        return blogMapper.getBlogTagVoPage(new Page(page,size));
    }

    @Override
    public Page<BlogTagVo> getBlogTagVoPageById(int page, int size, Long userId) {
        return blogMapper.getBlogTagVoPageById(new Page(page,size),userId);
    }

    /**
     * 分页查询博客
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public Map<String, Object> selectAllPage(int page, int size) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            Page<Blog> pageObject = new Page<>(page, size);
            Page infoObject = blogMapper.selectPage(pageObject, null);
            map.put("code", 1);
            map.put("msg", "success");
            map.put("data", infoObject.getRecords());
            map.put("total", infoObject.getTotal());
        } catch (Exception e) {
            map.put("code", 0);
            map.put("msg", "数据库错误...");
            map.put("data", null);
            map.put("total", 0);
        }
        return map;

    }

    /**
     * 根据id查询一条博客详情
     *
     * @param id
     * @return
     */
    @Override
    public Blog selectByIdOne(Long id) {
        try {
            Blog oneBlog = blogMapper.selectById(id);
            return oneBlog;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 插入一条博客
     *
     * @param
     * @return
     */
    @Override
    public R insertBlogOne(BlogTagVo blogTagVo) {

            try {
                QueryWrapper<Blog> qw = new QueryWrapper<>();
                qw.eq("title", blogTagVo.getTitle());
                Blog list = blogMapper.selectOne(qw);
                if (list != null) {
                    return R.failure(300,"标题重复！");
                }
                Blog blog = new Blog();
                blog.setTitle(blogTagVo.getTitle());
                blog.setContent(blogTagVo.getContent());
                blog.setCreateTime(blogTagVo.getCreateTime());
                blog.setUpdateTime(blogTagVo.getUpdateTime());
                int i = blogMapper.insert(blog);
                /**
                 * 插入标签 根据生成的id
                 */
                if (i == 1) {
                    if(blog.getId() != null){
                        List<Tag> listTag = blogTagVo.getTag();
                        int len = blogTagVo.getTag().size();
                        BlogTag[] blogTags = new BlogTag[len];
                        for (int j = 0; j < blogTagVo.getTag().size(); j++) {
                            Long tid = listTag.get(j).getId();
                            blogTags[j] = new BlogTag(blog.getId(), tid, new Date());

                        }

                        int blogTagLen = blogTagService.insertBlogTag(blogTags);
                        if (blogTagLen != len) {
                            return R.failure("标签插入失败");
                        }


                    }

                }else{
                    R.failure("没有id");
                }
                UserBlog userBlog = new UserBlog();
                userBlog.setCreateTime(new Date());
                userBlog.setBlogId(blog.getId());
                Long lId = Long.parseLong((String) StpUtil.getLoginId());
                userBlog.setUserId(lId);
//                System.out.println("userBlog:" + userBlog);
                userBlogMapper.insert(userBlog);
                return R.success("成功");
            } catch (Exception e) {
                throw new RuntimeException(e);

            }

    }

    /**
     * 根据id删除一条
     *
     * @param id
     * @return
     */
    @Override
    public int deleteBlogOne(Long id) {
        try {
            int i = blogMapper.deleteById(id);
            return i;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 跟新 博客一条
     *
     * @param blog
     * @return
     */
    @Override
    public R updateOne(BlogTagVo blogTagVo) {
        try {
            Blog upBlog = new Blog(blogTagVo.getId(),
                    blogTagVo.getTitle(),blogTagVo.getContent(),blogTagVo.getCreateTime(),blogTagVo.getUpdateTime());
            int i = blogMapper.updateById(upBlog);
            if(i == 1){
                List<Tag> listTagUpdate = blogTagVo.getTag();

                int len = listTagUpdate.size();
                if(len > 0){
                    BlogTag[] blogTagsUpdate = new BlogTag[len];
                    for (int j = 0; j < len; j++) {
                        Long tid = listTagUpdate.get(j).getId();
                        blogTagsUpdate[j] = new BlogTag(blogTagVo.getId(), tid, new Date());

                    }
                    int n = blogTagService.updateBlogTags(blogTagsUpdate);
                    if(n != len){
                        return R.failure(300,"标签更新失败");
                    }
                    return R.success("更新成功");
                }

            }

            return R.failure(201,"博客更新失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
